# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'd5fba0f3d80c4c6194f2e95feb823500': {  # 测试 线上的单笔限额2000 loki 支付宝
        'API_KEY': 'b1f65169d6b243bfb88f88cb954f4702',
        'gateway': 'http://g.xunshoupay.com/pay/toPay',
        'query_gateway': 'http://g.xunshoupay.com/pay/orderQuery',
    },
    'd62c4c9ecab34b6fb989ea833ce89a9b': {  # 线上的单笔限额2000 loki 支付宝
        'API_KEY': '3e404bfa730c46e8ab4c11b32ea4421d',
        'gateway': 'http://g.xunshoupay.com/pay/toPay',
        'query_gateway': 'http://g.xunshoupay.com/pay/orderQuery',
    },
    'eef0217bcfe349e286a563a79e022430': {  # 线上的单笔限额2000 loki 支付宝 88882018050910001159
        'API_KEY': '4c4e24f473904e8cb9eb2bfa46e9084c',
        'gateway': 'http://g.xunshoupay.com/pay/toPay',
        'query_gateway': 'http://g.xunshoupay.com/pay/orderQuery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'paySecret=%s' % key
    print s
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, app_id, key):
    sign = params['sign']
    params.pop('sign')
    params.pop('remark')
    params['payKey'] = app_id
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xunshoupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


# WEIXIN	微信扫码
# WEIXIN_H5	微信H5
# WEIXIN_WAP	微信WAP
# ALIPAY	支付宝扫码
# ALIPAY_H5	支付宝H5
# ALIPAY_WAP	支付宝WAP
# QQ	QQ钱包扫码
# QQ_H5	QQ钱包H5
# QQ_WAP	QQ WAP
# JD	京东支付扫码
# UNION_PAY	银联扫码
# OL_BANKING	在线网银
# EXPRESS_BANKING	快捷支付
def _get_pay_type(service):
    if service == 'alipay':
        return 'ALIPAY_WAP'
    elif service == 'quick':
        return 'EXPRESS_BANKING'
    elif service == 'qq':
        return 'QQ_WAP'
    elif service == 'jd':
        return 'JD'
    else:
        return 'WEIXIN_WAP'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('payKey', app_id),
        ('orderPrice', str(pay_amount)),
        ('payWayCode', _get_pay_type(service)),
        ('orderNo', str(pay.id)),
        ('orderTime', local_now().strftime('%Y%m%d%H%M%S')),
        ('productName', 'charge'),
        ('orderPeriod', '60'),
        ('returnUrl', '{}/pay/api/{}/xunshoupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/xunshoupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('remark', 'llllll'),
    ))

    p_dict['sign'] = generate_sign(p_dict, api_key)
    html_text = build_form(p_dict, _get_gateway(app_id))
    _LOGGER.info('xunshoupay before data: %s', p_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("xunshoupay notify data: %s", data)
    verify_notify_sign(data, app_id, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('xunshoupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['status']
    trade_no = ''
    total_fee = float(data['orderPrice'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('xunshoupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('payKey', app_id),
        ('orderNo', pay_order.id),
    ))
    p_dict['sign'] = generate_sign(p_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info('xunshoupay query, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = data['status']
        total_fee = float(data['orderPrice'])
        trade_no = pay_order.id

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == 'SUCCESS' and total_fee > 0:
            _LOGGER.info('xunshoupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
